package com.ruoyi.quartz.service.impl;

import com.ruoyi.alarmmanagement.domain.DmWarn;
import com.ruoyi.quartz.domain.InstantNumberMutation;
import com.ruoyi.quartz.domain.PressureMutation;
import com.ruoyi.quartz.mapper.RunWarnMapper;
import com.ruoyi.quartz.service.IRunWarnsService;
import com.ruoyi.quartz.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class RunWarnsServiceImpl implements IRunWarnsService {

    private static Logger _log = LoggerFactory.getLogger(RunWarnsServiceImpl.class);
    //预警类型
    private static Integer[] ALARM_TYPE = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22};


    @Autowired
    private RunWarnMapper runWarnMapper;

    //瞬时流量突变
    @Override
    public void job_InstantFlowMutationWarning(String dateTime) {
        _log.info("瞬时突变任务开始···");
//        Params param = pm.getParamByParamNameAndValue("AlarmType", String.valueOf(ALARM_TYPE[1]));
//        if(param.getDisplayflag() == 0) {
//            return;
//        }
        List<DmWarn> alarms = new ArrayList<DmWarn>();
//        String[] maxAlarmCode = new String[] {am.getMaxAlarmCode()};

        if(dateTime == null) return;

        String dateTimeS = dateTime + " 00:00:00";
        String dateTimeE = dateTime + " 23:59:59";

        //突变大于50显示、2021-12-17
        BigDecimal a = new BigDecimal(50);
        List<InstantNumberMutation> lists = runWarnMapper.job_InstantFlowMutationWarning(dateTimeS,dateTimeE);
        lists.stream()
                .filter(mu -> runWarnMapper.getAlarmRecordCount(mu.getLocation_nb(),ALARM_TYPE[20], DateUtil.getStringDate("yyyy-MM-dd"))==0)
                .filter(mu->a.compareTo(mu.getDiffAvgNumber()) < 0)
                .forEach(mutation ->{
                    Integer alarmType = ALARM_TYPE[20];
//                    String alarmcode = DateUtil.getRandomNumWithDate(alarmType,maxAlarmCode[0]);
                    String terminalid= mutation.getLocation_nb();
                    Date now = new Date();
                    Byte mark = 1;
                    Byte level = mutation.getLevel().byteValue();
                    String applyName = "系统";
                    Date terminaldate = mutation.getLastTerminalTime();
                    String description = String.format("昨日瞬时流量突变:瞬时流量平均值 %s;差值为  %s", mutation.getAvgNumber().toString(),mutation.getDiffAvgNumber().toString());
//                    DmWarn wn = new DmWarn(alarmcode, terminalid, alarmType, now,mark,level, applyName, terminaldate, description);
                    DmWarn wn = new DmWarn();
                    wn.setWarnStatus(0);
                    wn.setWarnType(ALARM_TYPE[20]);
                    wn.setHandleStatus(0);
                    wn.setRecentlyWarnTime(terminaldate);
                    wn.setDescription(description);
                    alarms.add(wn);
//                    maxAlarmCode[0] = alarmcode;//预警编号递增
                });
        if(alarms.size()>0) {
            batchAlarmsWithSize(alarms, 100);
        }

    }


    //分批插入预警-100
    private void batchAlarmsWithSize(List<DmWarn> alarms, int size) {
        int totalSize = alarms.size();//list长度
        int times = totalSize/size;
        int num = totalSize%size;
        times = num>0 ? times+1 : times;
        for(int i=0;i<times;i++) {
            if(i<times-1) {
                runWarnMapper.insertAlarmBatch(alarms.subList(100*i, 100*(i+1)));//插入预警记录到预警表
            }else if(num==0 && i==times-1){
                runWarnMapper.insertAlarmBatch(alarms.subList(100*i, 100*(i+1)));//插入预警记录到预警表
            }else if(num!=0 && i==times-1) {
                runWarnMapper.insertAlarmBatch(alarms.subList(100*i,100*i + num));//插入预警记录到预警表
            }
        }
    }

    //压力预警
    @Override
    public void job_PressMutationWarning(String dateTime) {
        _log.info("压力突变任务开始···");
        List<DmWarn> alarms = new ArrayList<DmWarn>();

        if(dateTime == null) return;

        String dateTimeS = dateTime + " 00:00:00";
        String dateTimeE = dateTime + " 23:59:59";

        List<PressureMutation> lists = runWarnMapper.pressMutationWarning(dateTimeS, dateTimeE);
        //BigDecimal a = new BigDecimal(0.3);
        lists.stream()
                .filter(mu -> runWarnMapper.getAlarmRecordCount(mu.getLocation_nb(),ALARM_TYPE[21], DateUtil.getStringDate("yyyy-MM-dd"))==0)
                //.filter(mu->a.compareTo(mu.getDiffAvgNumber()) < 0)
                .forEach(mutation ->{
//                    Integer alarmType = ALARM_TYPE[12];
//                    String terminalid = mutation.getLocation_nb();
//                    Date now = new Date();
//                    Byte mark = 1;
//                    Byte level = mutation.getLevel().byteValue();
//                    String applyName = "系统";
                    Date terminaldate = mutation.getLastTerminalTime();
                    String description = String.format("昨日压力数值突变:压力平均值 %s;最大差值为  %s", mutation.getAvgNumber().toString(),mutation.getDiffAvgNumber().toString());
                    DmWarn wn = new DmWarn();
                    wn.setWarnStatus(0);
                    wn.setWarnType(ALARM_TYPE[21]);
                    wn.setHandleStatus(0);
                    wn.setRecentlyWarnTime(terminaldate);
                    wn.setDescription(description);
                    alarms.add(wn);
                });
        if(alarms.size()>0) {
            batchAlarmsWithSize(alarms, 100);
        }
    }



//    @Override
//    public void job_DataIntegrityWarning(String dateTime) {
//        _log.info("数据完整性异常任务开始···");
//        List<DmWarn> alarms = new ArrayList<DmWarn>();
//        if(dateTime == null) return;
//
//        String dateTimeS = dateTime + " 00:00:00";
//        String dateTimeE = dateTime + " 23:59:59";
//
//        List<DataIntegrity> lists = runWarnMapper.dataIntegrityWarning(dateTimeS, dateTimeE);
//        _log.info("数据完整性任务lists长度"+lists.size());
//        lists.stream()
//                .filter(di -> runWarnMapper.getAlarmRecordCount(di.getLocation_nb(),ALARM_TYPE[14], DateUtil.getStringDate("yyyy-MM-dd"))==0)
//                .forEach(dataIntegrity ->{
////                    Integer alarmType = ALARM_TYPE[4];
////                    Integer terminalid= dataIntegrity.getTerminalId();
////                    Date now = new Date();
////                    Byte mark = 1;
////                    String applyName = "系统";
//                    Date terminaldate = dataIntegrity.getTerminalTime();
//                    String description = String.format("昨日数据异常: 采集频率 %d 分钟,上传频率 %d 小时,采集数据 %d 条。", dataIntegrity.getCollectionFrequency(),dataIntegrity.getUploadFrequency(),dataIntegrity.getNum());
//                    DmWarn wn = new DmWarn();
//                    wn.setWarnStatus(0);
//                    wn.setWarnType(ALARM_TYPE[14]);
//                    wn.setHandleStatus(0);
//                    wn.setRecentlyWartTime(terminaldate);
//                    wn.setDescription(description);
//                    alarms.add(wn);
//                });
//        if(alarms.size()>0) {
//            batchAlarmsWithSize(alarms, 100);
//        }
//    }

    //日用量预警
    @Override
    public void job_FreezeDay() throws ParseException {
        _log.info("日用量预警任务开始···");
        List<DmWarn> alarms = new ArrayList<DmWarn>();

        //获取当前日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date today = new Date();
        String endDate = sdf.format(today);//当前日期
        //获取三十天前日期
        Calendar theCa = Calendar.getInstance();
        theCa.setTime(today);
        theCa.add(Calendar.DATE, -8);//dateTimeS
        Date start = theCa.getTime();
        String startDate = sdf.format(start);//三十天之前日期

        theCa.setTime(today);
        theCa.add(Calendar.DATE, -1);//dateTimeS
        Date end = theCa.getTime();
        String endDate_ = sdf.format(end);//三十天之前日期

        String dateTimeS = startDate + " 00:00:00";
        String dateTimeE = endDate_ + " 00:00:00";

        List<PressureMutation> lists = runWarnMapper.FreezeDayWarning(dateTimeS, dateTimeE);
        lists.stream()
                .filter(mu -> runWarnMapper.getAlarmRecordCount(mu.getLocation_nb(),ALARM_TYPE[22], DateUtil.getStringDate("yyyy-MM-dd"))==0)
                .forEach(mutation ->{
                    Date terminaldate = mutation.getLastTerminalTime();
                    String description = "日用量异常: 前七天均值：" + mutation.getAvgNumber().toString() + ",昨日与均值相差：" + mutation.getDiffAvgNumber().toString();
                    DmWarn wn = new DmWarn();
                    wn.setWarnStatus(0);
                    wn.setWarnType(ALARM_TYPE[22]);
                    wn.setHandleStatus(0);
                    wn.setRecentlyWarnTime(terminaldate);
                    wn.setDescription(description);
                    alarms.add(wn);
                });
        if(alarms.size()>0) {
            batchAlarmsWithSize(alarms, 100);
        }


    }

}
